package com.amor.ui

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.SystemClock
import android.view.ViewGroup
import android.webkit.WebSettings
import androidx.webkit.ProxyConfig
import androidx.webkit.ProxyController
import androidx.webkit.WebViewFeature
import com.amor.widget.ExWebView
import com.hy.frame.util.ActUtil
import com.hy.frame.util.LogUtil


class ProxyWebActivity : BaseWebActivity() {

    private var proxyStr: String? = null

    private val mWeb by lazy {
        ExWebView(this)
    }

    @SuppressLint("SetJavaScriptEnabled")
    override fun initView() {
        super.initView()
        initStartTime = SystemClock.elapsedRealtime()
        LogUtil.d(TAG, "初始化WebView start")
        initWebSettings(mWeb.settings, WebSettings.LOAD_NO_CACHE)
        initClient(mWeb)
        mBinding?.container?.addView(mWeb, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        LogUtil.d(TAG, "初始化WebView end time=%sms".format(SystemClock.elapsedRealtime() - initStartTime))
        showConsole("初始化WebView耗时=%sms\n".format(SystemClock.elapsedRealtime() - initStartTime))
    }

    override fun initData() {
        super.initData()
        proxyStr = args?.getString(ARG_PROXY)
        if (!setWebProxy()) {
            showToast("当前手机不支持")
            mWeb.loadUrl(URL)
        }
    }

    private fun setWebProxy(): Boolean {
        if (proxyStr.isNullOrBlank())
            return false
        val proxy = ProxyConfig.Builder().addProxyRule(proxyStr!!).addDirect().build()
        if (WebViewFeature.isFeatureSupported(WebViewFeature.PROXY_OVERRIDE)) {
            ProxyController.getInstance().setProxyOverride(proxy, {
                mWeb.loadUrl(URL)
            }, {
                showToast("代理启用失败")
            })
            return true
        }
        return false
    }

    companion object {
        private const val TAG = "WebActivity"
        private const val ARG_PROXY = "arg_proxy"
        const val URL = "https://m.huize.com"
        fun startAct(cxt: Context?, host: String?, port: String?) {
            if (host.isNullOrBlank() || port.isNullOrBlank()) {
                return
            }
            val bundle = Bundle()
            bundle.putString(ARG_PROXY, "$host:$port")
            ActUtil.startAct(cxt, ProxyWebActivity::class.java, bundle)
        }
    }
}